package com.fand.stater.interceptor;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fand.stater.model.SysUserDetailDTO;
import com.fand.stater.context.UserInfoThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author: zhangjiabin
 * @Date: 2021/5/26
 * @Version 1.0
 */
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor, Ordered {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(Objects.nonNull(authentication)){
            Object principal = authentication.getPrincipal();
            if(Objects.nonNull(principal)&& principal instanceof SysUserDetailDTO){
                SysUserDetailDTO sysUserDetailDTO = (SysUserDetailDTO)principal ;
                UserInfoThreadLocal.set(sysUserDetailDTO);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoThreadLocal.remove();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
